package com.gouqi.tools.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gouqi.gouqitoolscommon.model.entity.User;
import com.gouqi.gouqitoolscommon.model.entity.UserTool;
import com.gouqi.tools.annotation.AuthCheck;
import com.gouqi.tools.common.BaseResponse;
import com.gouqi.tools.common.DeleteRequest;
import com.gouqi.tools.common.ErrorCode;
import com.gouqi.tools.common.ResultUtils;
import com.gouqi.tools.constant.UserConstant;
import com.gouqi.tools.exception.BusinessException;
import com.gouqi.tools.exception.ThrowUtils;
import com.gouqi.tools.model.dto.usertool.UserToolAddRequest;
import com.gouqi.tools.model.dto.usertool.UserToolQueryRequest;
import com.gouqi.tools.model.dto.usertool.UserToolUpdateRequest;
import com.gouqi.tools.model.vo.UserToolVO;
import com.gouqi.tools.service.UserService;
import com.gouqi.tools.service.UserToolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户调用工具关系接口
 */
@RestController
@RequestMapping("/userTool")
@Slf4j
public class UserToolController {

    @Resource
    private UserToolService userToolService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param toolAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<String> addUserTool(@RequestBody UserToolAddRequest toolAddRequest, HttpServletRequest request) {
        if (toolAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTool userTool = new UserTool();
        BeanUtils.copyProperties(toolAddRequest, userTool);
        userToolService.validUserTool(userTool, true);
        User loginUser = userService.getLoginUser(request);
        userTool.setUserId(loginUser.getId());
        boolean result = userToolService.save(userTool);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        String newUserToolId = userTool.getId();
        return ResultUtils.success(newUserToolId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserTool(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        String id = deleteRequest.getId();
        // 判断是否存在
        UserTool oldUserTool = userToolService.getById(id);
        ThrowUtils.throwIf(oldUserTool == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserTool.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = userToolService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param toolUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUserTool(@RequestBody UserToolUpdateRequest toolUpdateRequest, HttpServletRequest request) {
        if (toolUpdateRequest == null || toolUpdateRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTool userTool = new UserTool();
        BeanUtils.copyProperties(toolUpdateRequest, userTool);
        // 参数校验
        userToolService.validUserTool(userTool, false);
        User user = userService.getLoginUser(request);

        String id = toolUpdateRequest.getId();
        // 判断是否存在
        UserTool oldUserTool = userToolService.getById(id);
        ThrowUtils.throwIf(oldUserTool == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可修改
        if (!oldUserTool.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = userToolService.updateById(userTool);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserToolVO> getUserToolVOById(String id, HttpServletRequest request) {
        if (id.length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTool userTool = userToolService.getById(id);
        if (userTool == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(userToolService.getUserToolVO(userTool, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param userToolQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserToolVO>> listUserToolVOByPage(@RequestBody UserToolQueryRequest userToolQueryRequest, HttpServletRequest request) {
        long current = userToolQueryRequest.getCurrent();
        long size = userToolQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<UserTool> userToolPage = userToolService.page(new Page<>(current, size), userToolService.getQueryWrapper(userToolQueryRequest));
        return ResultUtils.success(userToolService.getUserToolVOPage(userToolPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param toolQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserToolVO>> listMyUserToolVOByPage(@RequestBody UserToolQueryRequest toolQueryRequest, HttpServletRequest request) {
        if (toolQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        toolQueryRequest.setUserId(loginUser.getId().toString());
        long current = toolQueryRequest.getCurrent();
        long size = toolQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<UserTool> userToolPage = userToolService.page(new Page<>(current, size), userToolService.getQueryWrapper(toolQueryRequest));
        return ResultUtils.success(userToolService.getUserToolVOPage(userToolPage, request));
    }

    // endregion

}
